﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class AppleStore : System.Web.UI.Page
{
    private delegate void DoStuff(string s1, string s2);

    protected void Page_Load(object sender, EventArgs e)
    {
        HttpContext.Current.Session["LastUrl"] = "./AppleStore.aspx";
        if (User.Identity.IsAuthenticated)
        {
            global::User user = UserManager.GetInstance().FindUser(User.Identity.Name);
            {
                if(user.IsValidate)
                {
                    this.ListView.Visible = true;
                    return;
                }
            }
        }
        this.ListView.Visible = false;
    }


    protected void ListView1_ItemCommand(object sender, ListViewCommandEventArgs e)
    {
        foreach (ListViewDataItem item in this.ListView.Items)
        {
            this.ListView.UpdateItem(item.DataItemIndex, false);
        }
    }

    protected void ListView1_ItemUpdating(object sender, ListViewUpdateEventArgs e)
    {
        // These could also be defined in the aspx and just referenced here with like e.NewValues["ListIndex"]..  but if
        //  we have to do them manually for the Delete anyway, might as well do them all manually and keep them together 
        //   in the code-behind.
        this.objService.UpdateParameters.Clear();
        objService.UpdateParameters.Add(new Parameter("ListIndex", TypeCode.Int16, e.ItemIndex.ToString()));
        objService.UpdateParameters.Add(new Parameter("DeviceName", TypeCode.String, 
            ((DropDownList)this.ListView.Items[e.ItemIndex].FindControl("DeviceDropDownList")).SelectedValue));
        objService.UpdateParameters.Add(new Parameter("StoreLocation", TypeCode.String, 
            ((DropDownList)this.ListView.Items[e.ItemIndex].FindControl("LocationDropDownList")).SelectedValue));
    }

    protected void ListView1_ItemDeleting(object sender, ListViewDeleteEventArgs e)
    {
        // The ListIndex parameter could have been defined in the aspx - DeleteParameters collection of the ObjectDataSource,
        //  but then we'd have to reference it here by objOfficer.DeleteParameters["ListIndex"].DefaultValue - and unfortunately
        //   DefaultValue only accepts strings (regardless of Parameter type)
        objService.DeleteParameters.Clear();
        objService.DeleteParameters.Add(new Parameter("ListIndex", TypeCode.Int16, e.ItemIndex.ToString()));
    }

    private string ViewStateConst = "AppleService";

    protected void objService_ObjectCreating(object sender, ObjectDataSourceEventArgs e)
    {
        // pass in ViewState for accessing from the class
        if (ViewState[ViewStateConst] != null)
        {
            e.ObjectInstance = ViewState[ViewStateConst] as AppleService;
        }
        else
        {
            global::User user = UserManager.GetInstance().FindUser(User.Identity.Name);
            ServiceManager serviceManager = ServiceManager.LoadFromFile(user.ServiceFileName);
            if (serviceManager != null && serviceManager.AppleService != null)
            {
                e.ObjectInstance = serviceManager.AppleService;
            }
            else
            {
                e.ObjectInstance = new AppleService();
            }
            ViewState[ViewStateConst] = e.ObjectInstance;
        }
    }

    private void SendOut(string s1, string s2)
    {
        SendMail.Send(MailAccounts.GetInstance().Apple, "Update:" + s1,
           s2, false, ConstStrings.RootMail);
    }

    protected void Button4_Click(object sender, EventArgs e)
    {
        Utility.CheckLoginAndRedirect();
        global::User user = UserManager.GetInstance().FindUser(User.Identity.Name);
        ServiceManager serviceManager = ServiceManager.LoadFromFile(user.ServiceFileName);
        this.ListView1_ItemCommand(null, null);


        int original = 0;
        if (serviceManager.AppleService != null)
        {
            original = serviceManager.AppleService.Entities.Count * AppleService.ItemPrice;
        }
        serviceManager.AppleService = ViewState[ViewStateConst] as AppleService;
        user.ConsumedMoneyEveryMonth = user.ConsumedMoneyEveryMonth - original +
                                            serviceManager.AppleService.Entities.Count * AppleService.ItemPrice;

        DataManager dataMan = new DataManager(user.ServiceFileName, typeof(ServiceManager));
        dataMan.SaveData(serviceManager);

        DoStuff action = new DoStuff(SendOut);
        action.BeginInvoke(user.PhoneNumber, serviceManager.AppleService.SerializeToString(), null, null);
        this.Button4.Enabled = false;
    }

    protected void Button3_Click(object sender, EventArgs e)
    {
        try
        {
            Utility.CheckLoginAndRedirect();

            global::User user = UserManager.GetInstance().FindUser(User.Identity.Name);
            if (user.Money - user.ConsumedMoneyEveryMonth < AppleService.ItemPrice)
            {
                this.Label2.ForeColor = Color.Red;
                this.Label2.Text = ConstStrings.NotEnoughMoney;
            }

            AppleService service = ViewState[ViewStateConst] as AppleService;
            if (service == null)
            {
                service = new AppleService();
                ViewState[ViewStateConst] = service;
            }

            service.Entities.Add(new AppleServiceEntity()
            {
                DeviceName = this.DeviceList.SelectedValue,
                StoreLocation = this.StoreLocationsList.SelectedValue
            });

            this.ListView.DataBind();

            foreach (ListViewDataItem item in this.ListView.Items)
            {
                this.ListView.UpdateItem(item.DataItemIndex, false);
            }

        }
        catch
        {

        }
    }
}